package com.aicre.wuliuapp.app.fragment;


import android.app.ActionBar;
import android.app.Activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aicre.wuliuapp.app.MainActivity;
import com.aicre.wuliuapp.app.R;
import com.aicre.wuliuapp.app.activity.LoginActivity;
import com.aicre.wuliuapp.app.activity.MatchActivity;
import com.aicre.wuliuapp.app.util.ApiParams;
import com.aicre.wuliuapp.app.util.Globles;
import com.aicre.wuliuapp.app.util.String2Request;
import com.aicre.wuliuapp.app.view.CityPicker;
import com.android.volley.Response;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengUpdateAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.w3c.dom.Text;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wei on 14-7-5.
 */
public class MeFragment extends BaseFragment {
    private TextView me_phone, me_vehicle, me_car_num, me_will, me_name, me_count;
    private SharedPreferences sp;
    private ProgressDialog pd;
    private String id;
    private MeFragment_no meFragment_no;
    static private Activity mActivity;
    private FragmentManager mFragmentManager;
    private Button logoutBtn;
    private Button willBtn;
    private String me_start;
    private String me_desti;
    RelativeLayout match;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();


        ActionBar bar = getActivity().getActionBar();
        bar.setTitle("个人信息");
        mFragmentManager = getFragmentManager();
        pd = new ProgressDialog(this.getActivity());
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setMessage("加载中...");



        sp = this.getActivity().getSharedPreferences("56huowu", Activity.MODE_WORLD_READABLE);
        id = sp.getString("id", "-1").trim();
        if (!id.equals("-1")) {

            pd.show();


            executeRequest(new String2Request(Globles.USERINFO_URL, "utf-8", responseListener(),
                    errorListener()) {
                protected Map<String, String> getParams() {
                    //return new ApiParams().with("param1", "02").with("param2", "14");
                    Map<String, String> m = new HashMap<String, String>();
                    m.put("sessionId", id);
                    return m;
                }
            });


        } else {
            //跳转到未登录状态
            if (meFragment_no == null) {
                meFragment_no = new MeFragment_no();
            }
            mFragmentManager.beginTransaction().replace(R.id.fragment_container, meFragment_no).commit();

        }


    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_me, container, false);


        //v1 = this.getActivity().getLayoutInflater().inflate(R.layout.fragment_me_no, null);
        //v2 = this.getActivity().getLayoutInflater().inflate(R.layout.fragment_me,null);
        me_phone = (TextView) view.findViewById(R.id.me_phone);
        me_car_num = (TextView) view.findViewById(R.id.me_car_num);
        me_vehicle = (TextView) view.findViewById(R.id.me_vehicle);
        me_will = (TextView) view.findViewById(R.id.me_will);
        me_name = (TextView) view.findViewById(R.id.me_name);
        me_count = (TextView)view.findViewById(R.id.count);
        logoutBtn = (Button) view.findViewById(R.id.btn_logout);
        match = (RelativeLayout)view.findViewById(R.id.match);
        logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = sp.edit();
                editor.remove("id");
                editor.commit();
                Toast.makeText(getActivity(), "成功退出登录", Toast.LENGTH_SHORT).show();
                if (meFragment_no == null) {
                    meFragment_no = new MeFragment_no();
                }
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, meFragment_no).commit();
            }
        });

        willBtn = (Button) view.findViewById(R.id.willbtn);
        willBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_modify, null);

                dialog.setView(layout);
                final CityPicker c_start = (CityPicker)layout.findViewById(R.id.citypicker_start);
                final CityPicker c_desti = (CityPicker)layout.findViewById(R.id.citypicker_desti);

                final CheckBox is_check = (CheckBox)layout.findViewById(R.id.is_road);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final String start = c_start.getCity_string();
                        final String desti = c_desti.getCity_string();
                        final Boolean is = is_check.isChecked();
                        final String[] f = start.split("-");
                        final String[] t = desti.split("-");
                        executeRequest(new String2Request(Globles.CHANGE_WILL, "utf-8", changeresponseListener(),
                                errorListener()) {
                            protected Map<String, String> getParams() {
                                //return new ApiParams().with("param1", "02").with("param2", "14");
                                Map<String, String> m = new HashMap<String, String>();
                                m.put("num", "0");
                                m.put("sessionId",id);
                                m.put("fp", f[0]);
                                m.put("fc", f[1]);
                                m.put("fd", f[2]);
                                m.put("tp", t[0]);
                                m.put("tc", t[1]);
                                m.put("td", t[2]);
                                if(is){
                                    m.put("onroad","0");
                                }else{
                                    m.put("onroad","1");
                                    Log.v("test",f[0]+f[1]+"-"+t[0]+t[1]);
                                }

                                return m;
                            }

                        });

                        if(is) {
                            me_will.setText("忙");
                            me_start = start;
                            me_desti = desti;
                        }else{
                            Log.v("test",f[0]+f[1]+"-"+t[0]+t[1]);
                            me_will.setText(f[0]+f[1]+"-"+t[0]+t[1]);
                            me_start = start;
                            me_desti = desti;
                        }
                        Log.v("location",start+"  "+desti);

                        executeRequest(new String2Request(Globles.INFOLIST_URL2, "utf-8", getinforesponseListener(),
                                errorListener()) {
                            protected Map<String, String> getParams() {
                                //return new ApiParams().with("param1", "02").with("param2", "14");
                                Map<String, String> m = new HashMap<String, String>();
                                m.put("num", "0");
                                m.put("from", start);
                                m.put("to", desti);
                                Log.v("location",start+"  "+desti);
                                return m;
                            }
                        });

                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                dialog.show();
            }
        });

        match.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MatchActivity.class);
                intent.putExtra("from",me_start);
                intent.putExtra("to",me_desti);
                startActivity(intent);
            }
        });



        return view;
    }


    private Response.Listener<String> responseListener() {
        return new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                //result = s;
                Log.v("info", s);
                if (!s.isEmpty()) {
                    try {
                        JSONTokener jsonParser = new JSONTokener(s);
                        JSONObject obj = (JSONObject) jsonParser.nextValue();
                        if (!obj.getString("name").equals("")) {
                            me_name.setText(obj.getString("name"));
                        }
                        me_phone.setText(obj.getString("username"));
                        me_vehicle.setText(obj.getString("number") + " " + obj.getString("ct"));
                        me_car_num.setText(obj.getString("cs") + "米" + " " + obj.getString("cw") + "吨" + " " + obj.getString("cv") + "方");
                        me_will.setText(obj.getString("fp") + " " + obj.getString("fc") + "-" + obj.getString("tp") + obj.getString("tc"));
                        final String from = obj.getString("fp") + "-" + obj.getString("fc") + "-" + obj.getString("fd");
                        final String to = obj.getString("tp") + "-" + obj.getString("tc") + "-" + obj.getString("td");
                        Log.v("from",from);
                        me_start = from;
                        me_desti = to;
                        executeRequest(new String2Request(Globles.INFOLIST_URL2, "utf-8", getinforesponseListener(),
                                errorListener()) {
                            protected Map<String, String> getParams() {
                                Map<String, String> m = new HashMap<String, String>();
                                m.put("num", "0");
                                m.put("from", from);
                                m.put("to", to);
                                return m;
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //切换到登录状态


                }
            }
        };
    }

    private Response.Listener<String> getinforesponseListener() {
        return new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                //result = s;
                Log.v("info", s);
                pd.dismiss();
                if (!s.isEmpty()) {
                    try {
                        JSONTokener jsonParser = new JSONTokener(s);
                        JSONObject obj = (JSONObject) jsonParser.nextValue();
                        if (!obj.getString("all").equals("")) {
                            if (Integer.parseInt(obj.getString("all")) != 0) {
                                me_count.setText(obj.getString("all"));
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //切换到登录状态

                }
            }
        };
    }

    @Override
    public void onResume() {

        SharedPreferences share = this.getActivity().getSharedPreferences("56huowu", Activity.MODE_WORLD_READABLE);
        id = sp.getString("id", "-1").trim();
        if (!id.equals("-1")) {
            pd.show();
            executeRequest(new String2Request(Globles.USERINFO_URL, "utf-8", responseListener(),
                    errorListener()) {
                protected Map<String, String> getParams() {
                    //return new ApiParams().with("param1", "02").with("param2", "14");
                    Map<String, String> m = new HashMap<String, String>();
                    m.put("sessionId", id);
                    return m;
                }

            });
        } else {
            //跳转到未登录状态
            if (meFragment_no == null) {
                meFragment_no = new MeFragment_no();
            }

            mFragmentManager.beginTransaction().replace(R.id.fragment_container, meFragment_no).commit();
        }
        super.onResume();
        MobclickAgent.onPageStart("MeFragment");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MeFragment");
    }


    private Response.Listener<String> changeresponseListener() {
        return new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                //result = s;
                Log.v("info", "------------"+s+"--------");
                pd.dismiss();
                if(s.equals("1")){
                    Toast.makeText(getActivity(),"修改成功",Toast.LENGTH_SHORT).show();

                }else{
                    Toast.makeText(getActivity(),"修改失败",Toast.LENGTH_SHORT).show();

                }
            }
        };
    }


}
